<!-- 封装关注组件，以后可能会有多个地方用到关注组件 -->
<template>
    <div class="follow-user">
        <van-button type="default" round size="small" :loading="followLoading" v-if="isFollowed"
            @click="onFollow(authorId)">已关注</van-button>
        <van-button type="info" round size="small" icon="plus" :loading="followLoading" v-else
            @click="onFollow(authorId)">关注</van-button>
    </div>
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user'

export default {
    name: 'FollowUser',
    props: {
        isFollowed: {
            type: Boolean,
            required: true
        },
        authorId: {
            type: [Number, String],
            required: true
        }
    },
    data() {
        return {
            followLoading: false, //关注按钮的加载状态
        }
    },
    methods: {
        // 关注作者或取消关注
        async onFollow(authorId) {
            try {
                this.followLoading = true

                if (this.isFollowed) {
                    // 已被关注，则取消关注
                    await deleteFollow(authorId)
                } else {
                    // 未被关注，则关注
                    await addFollow(authorId)
                }
                // 更新关注状态
                this.$emit('update:isFollowed', !this.isFollowed)
            } catch (err) {
                console.log('操作失败', err)
            }
            // 关闭按钮加载状态
            this.followLoading = false
        }
    }
}
</script>

<style lang="less" scoped>
    .follow-user {
        .van-button {
            width: 150px;
        }
    }
</style>